package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
)

func main() {
	currentDir, err := os.Getwd()
	if err != nil {
		fmt.Println(err.Error())
	}
	filename := filepath.Join(currentDir, "test1", "test.txt")
	writeFileContent(filename)
	readFileContent(filename)
	copyFile(filename, filepath.Join(currentDir, "test1", "test1.txt"))
}

func writeFileContent(filename string) {
	content := `afsdfgfdfgfdsafscxcv
				写点内容 咐啥杏(⊙o⊙)什么票一疑难杂症
经经工枯叶日3 顶替在模压`
	fd, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	fmt.Println(err)
	defer fd.Close()
	//n, err := fd.Write([]byte(content))
	n, err := fd.WriteString(content)
	fmt.Println(n, err)
}

func readFileContent(filename string) {
	fd, err := os.Open(filename)
	defer fd.Close()
	if err != nil {
		fmt.Println("打开文件出错", err.Error())
	} else {
		bs := make([]byte, 1024, 1024)
		n := -1
		for {
			n, err = fd.Read(bs)
			if n == 0 || err == io.EOF {
				fmt.Println("读取文件结束！")
				break
			}
			fmt.Println(string(bs[:n]))
		}
	}
}

func copyFile(srcFile, destFile string) {
	file1, err := os.Open(srcFile)
	if err != nil {
		fmt.Println("Open file1 failed: ", err)
	}
	file2, err := os.OpenFile(destFile, os.O_RDWR|os.O_CREATE, os.ModePerm)
	if err != nil {
		fmt.Println("Create file2 failed: ", err)
	}
	defer file1.Close()
	defer file2.Close()
	io.Copy(file2, file1)
}
